package com.aitech.hardwareconctrl

import android.media.AudioAttributes
import android.media.MediaPlayer
import android.text.TextUtils
import java.io.IOException
import kotlin.concurrent.Volatile

class AudioPlayerManager private constructor() {
    private var mMediaPlayer: MediaPlayer? = null
    private var mAudioPlayerPath: String? = null
    private var playerListener: AudioPlayerListener? = null
    private var isPlaying = false
    private var audioPlayingDuration = 0

    init {
        init()
    }

    private fun init() {
        mMediaPlayer = MediaPlayer()
        mMediaPlayer?.setScreenOnWhilePlaying(true) // 设置播放的时候一直让屏幕变亮
        //设置音乐播放
        mMediaPlayer?.setAudioAttributes(
            AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .build()
        )
        //网络流媒体的缓冲监听
        mMediaPlayer?.setOnBufferingUpdateListener(object : MediaPlayer.OnBufferingUpdateListener {
            override fun onBufferingUpdate(p0: MediaPlayer?, p1: Int) {

            }
        });
        //网络流媒体播放结束监听
        mMediaPlayer?.setOnCompletionListener {
            if (playerListener != null) {
                playerListener?.onAudioPlayerCompletion()
            }
        }
        //设置错误信息监听
        mMediaPlayer?.setOnErrorListener { mp, what, extra -> false }
        //音频源准备好后调用
        mMediaPlayer?.setOnPreparedListener {
            playerListener?.onAudioPlayerProgress((mMediaPlayer?.currentPosition ?: 0) / 1000, (mMediaPlayer?.duration ?: 0) / 1000, isPlaying)
            if (audioPlayingDuration <= 0) {
                start()
            } else {
                mMediaPlayer?.seekTo(audioPlayingDuration * 1000)
            }
        }
        //Seek操作完成后调用
//        mMediaPlayer?.setOnSeekCompleteListener { start() }

        //        mMediaPlayer.setOnTimedTextListener(new MediaPlayer.OnTimedTextListener() {
//            @Override
//            public void onTimedText(MediaPlayer mp, TimedText text) {
//            }
//        });
//
//        mMediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
//            @Override
//            public boolean onInfo(MediaPlayer mp, int what, int extra) {
//                return false;
//            }
//        });
    }


    /**
     * 播放
     */
    private fun start() {
        isPlaying = true
        if (mMediaPlayer?.isPlaying != true) {
            //异步准备
            mMediaPlayer?.start()
        }
    }

    /**
     * 资源准备
     *
     * @param path
     * @throws IOException
     */
    @Throws(IOException::class)
    private fun prepareAsync(path: String) {
        mMediaPlayer?.stop()
//        mMediaPlayer?.reset()
        mMediaPlayer?.setDataSource(path)
        //异步准备
        mMediaPlayer?.prepareAsync()
        mMediaPlayer?.prepare()
    }

    /**
     * 初始化资源数据，并准备数据
     *
     * @param path
     * @param audioPlayingDuration
     * @param audioPlayerListener
     */
    @Synchronized
    fun start(path: String, audioPlayingDuration: Int, audioPlayerListener: AudioPlayerListener?) {
        try {
            this.audioPlayingDuration = audioPlayingDuration
            //判断当前监听是否存在
            if (playerListener != null) {
                var currentPosition = -1
                //判断当前是否在播放，如果在，则获取播放进度，并暂停播放
                if (mMediaPlayer?.isPlaying == true) {
                    currentPosition = (mMediaPlayer?.currentPosition ?: 0) / 1000
                }
                playerListener?.onAudioPlayerPause(currentPosition)
            }
            //设置新的播放进度监听
            setListener(audioPlayerListener)
            this.mAudioPlayerPath = path
            //判断是否为同一个播放源
//            if (isIdenticalSource(path)) {
//                start()
//            } else {
            prepareAsync(path)
//            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 暂停播放
     *
     * @return
     */
    fun pause() {
        if (mMediaPlayer != null && mMediaPlayer?.isPlaying == true) {
            mMediaPlayer?.pause()
        }
        playerListener = null
    }

    /**
     * 停止播放，释放资源，可以用于：界面关闭，切换界面
     */
    fun stop() {
        if (mMediaPlayer != null && mMediaPlayer?.isPlaying == true) {
            mMediaPlayer?.pause()
            if (playerListener != null) {
                playerListener?.onAudioPlayerPause((mMediaPlayer?.currentPosition ?: 0) / 1000)
            }
        }
        if (mMediaPlayer != null) mMediaPlayer?.release()
        mAudioPlayerPath = ""
        playerListener = null
    }

    /**
     * 当前文件是否是 MediaPlayer 播放状态
     *
     * @param audioPlayerPath 当前文件
     * @return -1:标识不是当前播放文件  其他值：播放状态
     */
    fun isPlaying(audioPlayerPath: String): Int {
        if (isIdenticalSource(audioPlayerPath) && mMediaPlayer?.isPlaying == true) {
            return (mMediaPlayer?.currentPosition ?: 0) / 1000
        }
        return -1
    }

    /**
     * 判断是否为同一个音频源
     *
     * @param audioPlayerPath
     * @return
     */
    private fun isIdenticalSource(audioPlayerPath: String): Boolean {
        return TextUtils.equals(mAudioPlayerPath, audioPlayerPath)
    }


    /**
     * 设置播放读秒回调监听
     *
     * @param audioPlayerListener
     */
    fun setListener(audioPlayerListener: AudioPlayerListener?) {
        playerListener = audioPlayerListener
    }


    companion object {
        @OptIn(ExperimentalStdlibApi::class)
        @Volatile
        private var inStance: AudioPlayerManager? = null
        val instance: AudioPlayerManager?
            get() {
                if (inStance == null) {
                    synchronized(AudioPlayerManager::class.java) {
                        if (inStance == null) {
                            inStance = AudioPlayerManager()
                        }
                    }
                }
                return inStance
            }
    }
}
